/*
 * Copyright (c) 2015 Messcat. All rights reserved.
 */
package cc.messcat.web.system;

import cc.messcat.common.constant.CommonConstant;
import cc.messcat.common.model.ResponseBean;
import cc.messcat.common.util.CollectionUtil;
import cc.messcat.entity.system.McUser;
import cc.messcat.entity.system.Permission;
import cc.messcat.entity.system.Role;
import cc.messcat.service.system.PermissionService;
import cc.messcat.service.system.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * 权限模块
 *
 * @author Panda
 * @version 1.0
 */
@Controller
@RequestMapping("/permission")
public class PermissionController {

	@Autowired
	private PermissionService permissionService;

	@Autowired
	private UserService userService;

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "getPermissionAll", method = RequestMethod.GET)
	@ResponseBody
	public Object getPermissionAll() throws Exception {

		List<Permission> list = permissionService.retrievePermissionAll();
		Map<String, List<Permission>> resultMap = new HashMap<>();

		if (CollectionUtil.isListEmpty(list))
			return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, resultMap);

		// 封装数据,按需要进行数据重组！当接口被多次访问时，则不建议进行数据重组--by Panda
		List<Permission> menu = new ArrayList<>();
		List<Permission> front = new ArrayList<>();
		List<Permission> opt = new ArrayList<>();

		for (Permission p : list) {
			if (p.getPermissionType().equals(CommonConstant.PERMISSION_TYPE_MENU)) {
				menu.add(p);
				continue;
			}
			if (p.getPermissionType().equals(CommonConstant.PERMISSION_TYPE_FRONT)) {
				front.add(p);
				continue;
			}
			if (p.getPermissionType().equals(CommonConstant.PERMISSION_TYPE_OPT))
				opt.add(p);
		}
		Collections.sort(menu, new Comparator<Permission>(){
			@Override
			public int compare(Permission o1, Permission o2) {
				return o1.getId().compareTo(o2.getId());
			}
		});

		resultMap.put("menu", menu);
		resultMap.put("front", front);
		resultMap.put("opt", opt);

		return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, resultMap);
	}

	@RequestMapping(value = "getPermission/{id}", method = RequestMethod.GET)
	@ResponseBody
	public Object getPermission(@PathVariable Long id) throws Exception {
		Permission Permission = permissionService.retrievePermissionById(id);
		return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, Permission);
	}

	@RequestMapping(value = "addPermission", method = RequestMethod.POST)
	@ResponseBody
	public Object addPermission(Permission permission) throws Exception {
		permissionService.addPermission(permission);
		return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_ADD_SUCCESS);
	}

	@RequestMapping(value = "delPermission/{id}", method = RequestMethod.DELETE)
	@ResponseBody
	public Object delPermission(@PathVariable Long id) throws Exception {
		permissionService.removePermission(id);
		return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_DELETE_SUCCESS);
	}

	@RequestMapping(value = "updatePermission", method = RequestMethod.POST)
	@ResponseBody
	public Object updatePermission(Permission permission) throws Exception {
		permissionService.modifyPermission(permission);
		return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_UPDATE_SUCCESS);
	}

	@RequestMapping(value = "menu", method = RequestMethod.GET)
	@ResponseBody
	public Object getMenu() throws Exception {
		Subject subject = SecurityUtils.getSubject();
		String username = (String) subject.getPrincipals().getPrimaryPrincipal();
		McUser user = userService.retrieveUserWithRoleByUsernames(username);
		List<Permission> permissionList = new ArrayList<>();
		Set<Role> roleSet = user.getRoles();
		if (CollectionUtil.isSetEmpty(roleSet))
			return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_UPDATE_SUCCESS, permissionList);
		
		 Iterator<Role> it = roleSet.iterator();
         while(it.hasNext()){
            Role r = it.next();
            //该角色停用
            if("1".equals(r.getStatus())) {
             	it.remove();
             	continue;
         	}
            Set<Permission> permissionSet = r.getPermissions();
 			if (!CollectionUtil.isSetEmpty(permissionSet))
 				for (Permission p : permissionSet) {
 					if (p.getPermissionType().equals("0"))
 						permissionList.add(p);
 				}
         }

//		for (Role role : roleSet) {
//			//该角色停用
//			if("1".equals(role.getStatus())) {
//        		roleSet.remove(role);
//        		continue;
//        	}
//			Set<Permission> permissionSet = role.getPermissions();
//			if (!CollectionUtil.isSetEmpty(permissionSet))
//				for (Permission p : permissionSet) {
//					if (p.getPermissionType().equals("0"))
//						permissionList.add(p);
//				}
//		}

		Collections.sort(permissionList, new Comparator<Permission>() {
			public int compare(Permission o1, Permission o2) {
				try {
					return o1.getId().compareTo(o2.getId());
				} catch (Exception e) {
					return -1;
				}
			}
		});

		return new ResponseBean(CommonConstant.SUCCESS_CODE_200, "获取菜单成功", permissionList);
	}

	/**
	 * 获取子菜单下的功能列表
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "options/{id}", method = RequestMethod.GET)
	@ResponseBody
	public Object getOptions(@PathVariable Long id) throws Exception {
		List<Permission> options = permissionService.retrieveSubPermissionOptions(id);
		return new ResponseBean(CommonConstant.SUCCESS_CODE_200, "获取子菜单功能列表成功", options);
	}
}